<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <!-- 
        之前通信方法一的方法可以通过 sync 关键字被简化，
        <hello-world v-bind:val.sync="num"></hello-world> => <hello-world v-bind:val="num" @update:val="newValue => num = newValue"></hello-world>
        然后你需要在子组件中改变父组件数据的时候， 需要触发以下的自定义事件: 
        this.$emit("update:val", newValue)
     -->
    <div id="app">
        <hello-world v-bind:val.sync="num"></hello-world>
        <button @click="doubleAdd">父组件加2苹果</button>
        <div>你买了{{num}}个苹果</div>
    </div>
    
    <script src="../../node_modules/vue/dist/vue.js"></script>
    <script>
        // 子组件
        const HelloWorld = {
            template: `<div class="hello">
                            <button @click="add">子组件加1苹果</button>
                            <div>你买了{{val}}个苹果</div>
                        </div>`,
            props: {
                val: Number
            },
            methods: {
                add() {
                    this.val += 1;
                    this.$emit('update:val', this.val);
                }
            }
        };

        // 父组件
        new Vue({
            el: '#app',
            name: 'App',
            components: {
                HelloWorld
            },
            data() {
                return {
                    num: 1
                }
            },
            methods: {
                doubleAdd(){
                    this.num += 2;
                }
            }
        });
    </script>
</body>
</html>